// LinkList.cpp

enum Status
{
    OK,
    ERROR,
};

typedef struct LNode{
    int data;
    LNode *next;
}LNode, *LinkList;

Status GetElem_L(LinkList L, int i, int &e)
{
    LNode *p = L->next;
    int j = 0;

    while (p && j < i)
    {
        p = p->next;
        ++j;
    }

    if (!p || j >= i)
    {
        return ERROR;
    }

    e = p->data;
    
    return OK;
}

Status ListInsert_L(LinkList L, int i, int e)
{
    LNode *p = L->next;
    int j = 0;

    while(p && j < i)
    {
        p = p->next;
        ++j;
    }

    if(!p || j >= i)
    {
        return ERROR;
    }

    LNode *s = new LNode;
    s->data = e;
    s->next = p->next;

    p->next = s;

    return OK;
}

Status ListDelete_L(LinkList L, int i, int &e)
{
    LNode *p = L->next;
    int j = 0;

    while(p && j < i)
    {
        p = p->next;
        ++j;
    }

    if(!p || j >= i)
    {
        return ERROR;
    }

    LNode *s = p->next;
    e = p->next->data;
    p->next = p->next->next;

    delete(s);

    return OK;
}

void CreateList_L(LinkList &L, int n)
{
    L = new LNode;
    L->next = NULL;

    int i = 0;
    while(i < n)
    {
        LNode *s = new LNode;
        s->data = 0;
        s->next = NULL;

        L->next = s;
        L = L->next;
        
        ++i;
    }

    L->next = NULL;
}

void MergeList_L(LinkList &La, LinkList &Lb, LinkList &Lc)
{
    // 已知单链线性表La和Lb的元素按值非递减排列，归并La和Lb得到新的单链线性表Lc，Lc的元素也按值非递减排列。
    LNode *pa = La->next;
    LNode *pb = Lb->next;

    LNode *pc = new LNode;
    Lc = pc = pa;

    while(pa && pb)
    {
        if(pa->data <= pb->data)
        {
            pc->next = pa;
            pc = pa;
            pa = pa->next;
        }
        else
        {
            pc->next = pb;
            pc = pb;
            pb = pb->next;
        }
    }

    pc->next = pa ? pa : pb;

    delete(Lb);
}
